package com.ikangtai.shecare.common.util;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.eventBusMsg.LoginDownloadMsg;
import com.ikangtai.shecare.common.eventBusMsg.LoginInfo;
import com.ikangtai.shecare.personal.RegisterActivity;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;

/**
 * Created by ikangtai on 2016/8/18.
 */
public class LoginUtil {

    private Context context;
    private LoginInfo loginInfo = new LoginInfo();
    private String buildType;
    private int registerSimpleType = 0;
    private String openID = null;
    private EditText login_validate_code;
    private ImageView login_validate_image;
    private ProgressDialog progressDialog;
    private static DBManager dbManager;
    private LoginDownloadMsg loginDownloadMsg = new LoginDownloadMsg();

    private static final int LOGIN_OK = 1;
    private static final int LOGIN_NOK = 2;
    private static final int NO_USER = 3;
    private static final int PASSWORD_WRONG = 4;
    private static final int PASSWORD_WRONG_WITH_VALIDATE_CODE = 5;
    private static final int VALIDATE_CODE_NO = 6;
    private static final int VALIDATE_CODE_WRONG = 7;
    private static final int VALIDATE_CODE_OVERDUE = 8;
    private static final int FAIL_TO_GET_DB_VERSION = 9;

    private final int NO_DEVICEID_PARAM_FOUND = 0;
    private final int NO_DEVICEID_FOUND = 1;
    private final int SAME_DEVICEID_FOUND = 2;
    private final int DIFF_DEVICEID_FOUND = 3;

    public LoginUtil(Context context) {
        this.context = context;
        buildType = context.getResources().getString(R.string.buildType);
        dbManager = new DBManager(context);
    }

    private void doLogin(final String userName, final String userPswd, final String openID) {
        OKHttpUtil okHttpClient = new OKHttpUtil(context);
        loginInfo.setUserName(userName);
        loginInfo.setUserPswd(userPswd);

        String appendUrl;

        if (buildType.equals("god"))
            appendUrl = "login/internal.json";
        else
            appendUrl = "login/login.json";

        try {
            okHttpClient.add("emailOrPhone", userName);

            if (!buildType.equals("god")) {
                okHttpClient.add("password", userPswd);

                String phoneID = DeviceInfo.getDeviceID();
                okHttpClient.add("phoneID", phoneID);
                AppLog.i("phoneID = " + phoneID);
            }

            if(!(openID == null || openID.length()<=0)){
                okHttpClient.add("serviceID", openID);
            }

            if (login_validate_code.getVisibility() == View.VISIBLE) {
                okHttpClient.add("verifyCode", login_validate_code.getText().toString().trim());
            }
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {
                @Override
                public void onFailure(Request request, IOException e) {
                    sendNOKResp();
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");
                        AppLog.e("" + respCode);
                        if (200 == respCode) {

                            if(!(openID == null || openID.length()<=0)){
                                App.userName = respJSONObj.getString("emailOrPhoneNumber");
                            }else {
                                App.userName = userName;
                            }

                            App.userPswd = userPswd;
                            App.authToken = respJSONObj.getString("authToken");
                            loginInfo.setRespCode(LOGIN_OK);
                            if (!respJSONObj.isNull("isDeviceChanged")) {
                                loginInfo.setIsDeviceChanged(respJSONObj.getInt("isDeviceChanged"));
                            } else {
                                loginInfo.setIsDeviceChanged(1);
                            }
                            sendOKResp(loginInfo);
                            AppLog.i("login onResponse success! App.authToken = " + App.authToken);
                        } else if (202 == respCode) {
                            LoginInfo loginInfo = new LoginInfo();
                            loginInfo.setRespCode(NO_USER);
                            EventBus.getDefault().post(loginInfo);

                        } else if (203 == respCode) {
                            LoginInfo loginInfo = new LoginInfo();
                            loginInfo.setRespCode(PASSWORD_WRONG);
                            EventBus.getDefault().post(loginInfo);

                        } else if (204 == respCode) {
                            LoginInfo loginInfo = new LoginInfo();
                            loginInfo.setRespCode(PASSWORD_WRONG_WITH_VALIDATE_CODE);
                            loginInfo.setImageUrl(respJSONObj.getString("verifyCodeImageURL"));
                            EventBus.getDefault().post(loginInfo);

                        } else if (207 == respCode) {
                            LoginInfo loginInfo = new LoginInfo();
                            loginInfo.setRespCode(VALIDATE_CODE_NO);
                            loginInfo.setImageUrl(respJSONObj.getString("verifyCodeImageURL"));
                            EventBus.getDefault().post(loginInfo);

                        } else if (208 == respCode) {
                            LoginInfo loginInfo = new LoginInfo();
                            loginInfo.setRespCode(VALIDATE_CODE_WRONG);
                            loginInfo.setImageUrl(respJSONObj.getString("verifyCodeImageURL"));
                            EventBus.getDefault().post(loginInfo);

                        } else if (209 == respCode) {
                            LoginInfo loginInfo = new LoginInfo();
                            loginInfo.setRespCode(VALIDATE_CODE_OVERDUE);
                            loginInfo.setImageUrl(respJSONObj.getString("verifyCodeImageURL"));
                            EventBus.getDefault().post(loginInfo);

                        } else if (270 == respCode) {
                            LoginInfo loginInfo = new LoginInfo();
                            loginInfo.setRespCode(FAIL_TO_GET_DB_VERSION);
                            loginInfo.setAuthToken(respJSONObj.getString("authToken"));
                            EventBus.getDefault().post(loginInfo);
                        } else if (216 == respCode) {
                            Intent intent = new Intent(context, RegisterActivity.class);
                            intent.putExtra("registerSimpleType", registerSimpleType);
                            intent.putExtra("openID", openID);
                            context.startActivity(intent);
                        } else {
                            sendNOKResp();
                            AppLog.i("login onResponse failed! respCode is:" + respCode);
                        }
                    } catch (JSONException e) {
                        sendNOKResp();
                        AppLog.i("login onResponse failed!");
                        e.printStackTrace();
                    }
                }

                private void sendNOKResp() {
                    LoginInfo loginInfo = new LoginInfo(LOGIN_NOK);
                    EventBus.getDefault().post(loginInfo);
                }

                private void sendOKResp(LoginInfo loginInfo) {
                    AppLog.i("begin EventBus post after login!");
                    EventBus.getDefault().post(loginInfo);
                    AppLog.i("begin EventBus post after login2!");
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Subcriber
    private void handleLogin(LoginInfo loginInfo) {
        switch (loginInfo.getRespCode()) {
            case LOGIN_OK:
//                AppLog.i("begin EventBus post after login3!");
//                if (!isDataDownloaded())

//                else
//                    EventBus.getDefault().post(loginDownloadMsg);
                downloadData(loginInfo.getIsDeviceChanged());
                break;

            case LOGIN_NOK:
                dismissProgressDialog();
                break;

            case NO_USER:
                dismissProgressDialog();
                Toast.makeText(context, R.string.name_or_pass_fail, Toast.LENGTH_SHORT).show();
                break;
            case PASSWORD_WRONG:
                dismissProgressDialog();
                Toast.makeText(context, R.string.name_or_pass_fail, Toast.LENGTH_SHORT).show();
                break;
            case PASSWORD_WRONG_WITH_VALIDATE_CODE:
                dismissProgressDialog();
                login_validate_code.setVisibility(View.VISIBLE);
                login_validate_image.setVisibility(View.VISIBLE);
                Toast.makeText(context, R.string.name_or_pass_fail, Toast.LENGTH_SHORT).show();
                Glide.with(context).load(loginInfo.getImageUrl()).into(login_validate_image);
                break;
            case VALIDATE_CODE_NO:
                dismissProgressDialog();
                Toast.makeText(context, R.string.captcha_null, Toast.LENGTH_SHORT).show();
                Glide.with(context).load(loginInfo.getImageUrl()).into(login_validate_image);
                break;
            case VALIDATE_CODE_WRONG:
                dismissProgressDialog();
                Toast.makeText(context, R.string.captcha_fail, Toast.LENGTH_SHORT).show();
                Glide.with(context).load(loginInfo.getImageUrl()).into(login_validate_image);
                break;
            case VALIDATE_CODE_OVERDUE:
                dismissProgressDialog();
                Toast.makeText(context, R.string.captcha_out, Toast.LENGTH_SHORT).show();
                Glide.with(context).load(loginInfo.getImageUrl()).into(login_validate_image);
                break;
            case FAIL_TO_GET_DB_VERSION:
                dismissProgressDialog();
                App.authToken = loginInfo.getAuthToken();
                break;
        }
    }

    private void downloadData(int deviceId) {
        switch (deviceId) {
            case NO_DEVICEID_PARAM_FOUND:
                AppLog.i("Login NO_DEVICEID_PARAM_FOUND!");
                break;
            case NO_DEVICEID_FOUND:
                AppLog.i("Login NO_DEVICEID_FOUND!");
                downloadData();
                break;
            case SAME_DEVICEID_FOUND:
                AppLog.i("Login SAME_DEVICEID_FOUND!");
                if (dbManager.hasUser(App.userName)) {
                    loginDownloadMsg.setAllDataReady();
                    EventBus.getDefault().post(loginDownloadMsg);
                } else {
                    downloadData();
                }
                break;
            case DIFF_DEVICEID_FOUND:
                downloadData();
                break;
        }
    }

    private void downloadData() {
//        downloadUserPreferences();
//        downloadCollectedArticles();
//        downloadHealthAndAvatar();
//        downloadCompleteTaskIDs();
//
//        //download其他数据，如温度记录，收藏，LH试纸等
//        getRecordDatas();
//        downloadAlgorithmData();
//        getRecordLHAndHCGAndBUDatas(); // 获取服务器所有试纸信息
//        getAllTask();
    }

    private void downloadUserPreferences() {

        dbManager.insertUserPreference(App.userName, App.userPswd);
        dbManager.updateUserPreference(App.userName, "openID", openID);

        OKHttpUtil okHttpClient = new OKHttpUtil(context);

        String appendUrl = "hardware/obtainMacID.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("hardwareType", 1);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {
                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {

                    try {
                        String resultStr = response.body().string();
                        AppLog.i("obtainMacID:" + resultStr);
                        JSONObject respJSONObj = new JSONObject(resultStr);

                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            AppLog.i("obtainMacID onResponse success!");
//                            downloadMacIDData2DB(respJSONObj);
                            loginDownloadMsg.downloadUserPreferenceOK = true;
                            EventBus.getDefault().post(loginDownloadMsg);
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            downloadUserPreferences();
                        } else {
                            loginDownloadMsg.downloadUserPreferenceOK = true;
                            EventBus.getDefault().post(loginDownloadMsg);
                            AppLog.i("obtainMacID onResponse failed! respCode is:" + respCode);
                        }
                    } catch (JSONException e) {
                        AppLog.i("obtainMacID onResponse failed!");
                        e.printStackTrace();
                        loginDownloadMsg.downloadUserPreferenceOK = true;
                        EventBus.getDefault().post(loginDownloadMsg);
                    }
                    AppLog.i("obtainMacID now!");
                }

            });
        } catch (JSONException e) {
            AppLog.i("obtainMacID JSONException!");
            e.printStackTrace();
            loginDownloadMsg.downloadUserPreferenceOK = true;
            EventBus.getDefault().post(loginDownloadMsg);
        }

    }

    private void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

}
